<?php

namespace App\Kuafu\ProductMenu\Controller\B;

use App\Exceptions\BaseException;
use App\Exceptions\CustomValidateException;
use App\Kuafu\Category\Service\CategoryService;
use App\Kuafu\Config\Service\ConfigService;
use App\Kuafu\Product\Exceptions\ProductException;
use App\Kuafu\ProductMenu\Enum\ProductMenuCodeEnum;
use App\Kuafu\ProductMenu\Exceptions\ProductMenuException;
use App\Kuafu\ProductMenu\Model\ProductMenu;
use App\Kuafu\ProductMenu\Service\ProductMenuBatchService;
use App\Kuafu\ProductMenu\Service\ProductMenuService;
use App\Kuafu\ProductMenu\Validate\ProductMenuV2Validate;
use App\Kuafu\ProductMenu\Validate\ProductMenuValidate;
use App\Kuafu\Shop\Model\Shop;
use App\Kuafu\User\Exceptions\UserException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use App\Kuafu\Base\Controller\BaseController;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

class ProductMenuController extends BaseController
{
    /**
     * 获取菜单列表
     * @param Request $request
     * @return JsonResponse
     */
    public function getMenu(Request $request): JsonResponse
    {
        $productMenuId = (int)$request->get('productMenuId', 0);
        $name          = (string)$request->get('name', '');
        $pageSize      = (int)$request->get('pageSize', 20);
        $pageNum       = (int)$request->get('pageNum', 1);
        $shopIds       = (string)$request->get('shopIds');
        $dimCode       = $request->get('dimCode', '');
        $sortField     = (string)$request->get('sortField', '');
        $sortType      = (string)$request->get('sortType', 'desc');

        $valid = ProductMenuValidate::getMenu($request->all());
        if ($valid) {
            return $this->fail(ProductMenuCodeEnum::ERR_FOOD_MENUS_PARAM, $valid);
        }

        $shopIds = explode(',', $shopIds);
        $shopIds = array_filter($shopIds);

        if (empty($shopIds) && empty($dimCode)) {
            $menuIds = [];
        } else {
            $menuIds = Shop::query()
                           ->when($shopIds, function ($query) use ($shopIds) {
                               $query->whereIn('id', $shopIds);
                           })
                           ->when($dimCode, function ($query) use ($dimCode) {
                               if (!is_numeric($dimCode)) {
                                   $query->Where('name', 'like', '%' . $dimCode . '%');
                               } else {
                                   $query->where('id', $dimCode)->orWhere('shopCode', $dimCode);
                               }
                           })
                           ->get()
                           ->pluck('menuId')
                           ->unique()
                           ->toArray();

        }

        return $this->success(ProductMenuService::getMenu($productMenuId, $name, $pageSize, $pageNum, $menuIds,
            $sortField, $sortType));
    }


    /**
     * 新增菜单
     *
     * @param Request $request
     * @return JsonResponse
     * @throws ProductException
     * @throws ProductMenuException
     */
    public function addMenu(Request $request): JsonResponse
    {
        $name         = $request->post('name');
        $desc         = (string)$request->post('desc', '');
        $productList  = $request->post('productList');
        $categoryList = $request->post('categoryList');
        $valid        = ProductMenuValidate::addMenu($request->all());
        if ($valid) {
            return $this->fail(ProductMenuCodeEnum::ERR_FOOD_MENUS_PARAM, $valid);
        }

        ProductMenuService::addMenu((int)$request->header('brandId'), $name, $desc, $productList, $categoryList);

        return $this->success();
    }


    /**
     * 编辑菜单
     *
     * @param Request $request
     * @param $menuId
     * @return JsonResponse
     * @throws ProductMenuException
     * @throws UserException
     * @throws ProductException
     */
    public function setMenu(Request $request, $menuId): JsonResponse
    {
        $menuId       = (int)$menuId;
        $name         = (string)$request->get('name', '');
        $desc         = (string)$request->post('desc', '');
        $productList  = $request->post('productList');
        $categoryList = $request->post('categoryList');

        $valid = ProductMenuValidate::setMenu($request->all() + ['menuId' => $menuId]);
        if ($valid) {
            return $this->fail(ProductMenuCodeEnum::ERR_FOOD_MENUS_PARAM, $valid);
        }

        ProductMenuService::setMenu((int)$request->header('brandId'), $menuId, $name, $desc, $productList,
            $categoryList);
        return $this->success();
    }

    /**
     * 上下架菜单
     * @param Request $request
     * @param string $productMenuId
     * @return JsonResponse
     * @throws ProductMenuException
     */
    public function setMenuStatus(Request $request, $productMenuId): JsonResponse
    {
        $productMenuId = (int)$productMenuId;
        $status        = $request->get('status');

        $valid = ProductMenuValidate::setMenuStatus($request->all() + ['productMenuId' => $productMenuId]);
        if ($valid) {
            return $this->fail(ProductMenuCodeEnum::ERR_FOOD_MENUS_PARAM, $valid);
        }

        ProductMenuService::setMenuStatus($productMenuId, $status);

        return $this->success();
    }

    /**
     * 删除菜单
     * @param Request $request
     * @param string $productMenuId
     * @return JsonResponse
     * @throws ProductMenuException
     */
    public function delMenu(Request $request, $productMenuId): JsonResponse
    {
        $productMenuId = (int)$productMenuId;
        if (!$productMenuId) {
            return $this->fail(ProductMenuCodeEnum::ERR_FOOD_MENUS_PARAM, 'productMenuId不能为空');
        }

        ProductMenuService::delMenu((int)$request->header('brandId'), $productMenuId);

        return $this->success();
    }

    /**
     * 获取菜单下的所有菜品
     * @param Request $request
     * @param $productMenuId
     * @return JsonResponse
     */
    public function productLists(Request $request, $productMenuId): JsonResponse
    {
        $brandId = (int)$request->header('brandId');

        // 菜品列表
        $productList = ProductMenuService::productLists($productMenuId);

        // 分类
        $categoryList = CategoryService::getCategoryList($brandId, $productMenuId, ['id', 'pid','name']);

        // 菜单信息
        $menu = ProductMenu::query()->select(['id', 'name as menuName', 'desc'])->find($productMenuId);

        $data = [
            'menuGiftCategory' => ConfigService::getConfigDetail("menu", "giftCategory")["value"],
            'menu'             => $menu,
            'categoryList'     => $categoryList,
            'productList'      => $productList,
        ];
        return $this->success($data);
    }

    /**
     * 批量下发菜品
     *
     * @param Request $request
     * @return JsonResponse
     * @throws ProductMenuException
     * @throws UserException
     */
    public function batchMenus(Request $request): JsonResponse
    {
        $shopIds    = $request->get('shopIds');
        $productIds = $request->get('productIds');
        $handleType = (int)$request->get('handleType', 1);

        (new ProductMenuBatchService())->batchSend($shopIds, $productIds, $handleType);

        return $this->success();
    }

    /**
     * 置顶操作
     *
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     * @throws CustomValidateException
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface|BaseException
     */
    public function top(Request $request, int $id): JsonResponse
    {
        $params = ProductMenuV2Validate::topValidate($request->merge(["menuId" => $id])->all());
        ProductMenuService::top($params);
        return $this->success();
    }

    /**
     * 单个菜单导出
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     */
    public function menuExport(Request $request, int $id): JsonResponse
    {
        ProductMenuService::menuExportById($id, 1);
        return $this->success();
    }
}
